package com.ywy.config;

import com.ywy.entity.Link;
import com.ywy.entity.ResType;
import com.ywy.service.LinkService;
import com.ywy.service.ResTypeService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 初始化加载数据
 *
 * @author ywy
 * @date 2022/8/18 19:58
 */
@Component
public class ApplicationInitialize implements ServletContextListener, ApplicationContextAware {
    public static Map<Integer, ResType> resTypeMap = new HashMap<>();

    private static ApplicationContext applicationContext;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        this.loadData(servletContextEvent.getServletContext());
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 加载数据到application缓存中
     * @param application
     */
    public void loadData(ServletContext application) {
        // 查询所有资源类别
        ResTypeService resTypeService = (ResTypeService) applicationContext.getBean("resTypeServiceImpl");
        List<ResType> allResTypeList = resTypeService.listAll();
        for(ResType resType : allResTypeList) {
            resTypeMap.put(resType.getId(), resType);
        }
        application.setAttribute("allResTypeList", allResTypeList);

        // 查询所有友情链
        LinkService linkService = (LinkService) applicationContext.getBean("linkServiceImpl");
        List<Link> allLinkList = linkService.listAll();
        application.setAttribute("allLinkList", allLinkList);
    }
}
